package 基础;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

//udp服务端
public class UdpEchServer {
    private DatagramSocket socket = null;

    //在创建的时候规定端口号
    public UdpEchServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("启动服务器");
        while(true){
            //一直在处理请求和发回响应
//            1.读取请求并解析
            //Udp使用数据报，所以使用DatagramPacket
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024],1024);
            //从内核的缓存区中取出数据放入requestPacket中
            socket.receive(requestPacket);
            //将requestPacket中的数据(字节数组)转换成String类型
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
//            2.根据请求得出响应
            String response = process(request);
//            3，将响应返回客户端
            //继续使用数据报的方式返回 
            //数据报中包含，响应的内容，长度，请求方的地址
            DatagramPacket respondPacket = new DatagramPacket(response.getBytes(),response.getBytes().length,requestPacket.getSocketAddress());
            socket.send(respondPacket);

            //打印日志
            System.out.printf("[客户端IP= %s,客户端端口=%d] req = %s,resp = %s\n",requestPacket.getAddress().toString(),
                    requestPacket.getPort(),request,response);

        }
    }

    public  String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchServer udpEchServer = new UdpEchServer(9090);
        udpEchServer.start();
    }
}
